package com.qy.db.pool;

import java.sql.Connection;

import com.qy.util.LogUtil;
import com.qy.util.NetConfig;
import com.qy.util.NetConfigUtil;
import com.qy.util.ServerConfigUtil;

/**
 * 数据库连接池管理类
 * 
 */
public class DBPoolMgr {
	
	public static final String dbUrl = "jdbc:mysql://%s:%s/%s?useUnicode=true&characterEncoding=UTF-8";
	
//	private static IDBPool basePool;
	private static IDBPool strategyPool;
//	private static IDBPool logPool;
	
//	public static String BASE_POOL_NAME = "base";
	public static String STRATEGY_POOL_NAME = "mysql";
//	public static String LOG_POOL_NAME = "log";

	private static NetConfig mainDBXml;
	private static int mainDBMaxConn = 5;
	private static int mainDBFllow = 3;
//	private static int logDBMaxConn = 5;
//	private static int logDBFllow = 3;

	public static boolean init() {
		mainDBXml = NetConfigUtil.getNetConfigXml(3, 1);
		mainDBMaxConn = ServerConfigUtil.getInt("mysql.maxconn");
		mainDBFllow = ServerConfigUtil.getInt("mysql.fallow");
		return initPool(true, true, true);
	}

	
	private static String getMainDBUrl() {
		if (mainDBXml != null) {
			return String.format(dbUrl, mainDBXml.getAddress(), mainDBXml.getPort(), mainDBXml.getName());
		}
		return "";
	}


	public static boolean initPool(boolean isInitBaseDB, boolean isInitMainDB, boolean isInitLogDB) {
		
		
		if (isInitMainDB) {
			strategyPool = createPools(STRATEGY_POOL_NAME, getMainDBUrl(), mainDBXml.getUser(), mainDBXml.getPassword());
			if (strategyPool == null) {
				return false;
			}
		}
		return true;
	}

	/**
	 * 检查连接池状态是否挂掉，如挂了重新初始化
	 * 
	 * @param checkStrategy
	 *            是否检查游戏库
	 * @param checkLog
	 *            是否检查日志库
	 */
	public static void checkConnectionPool(boolean checkBase, boolean checkMain, boolean checkLog) {
		boolean initBase = false;
		boolean initStrategy = false;
		boolean initLog = false;
//		if(checkBase){
//			if (basePool == null || basePool.getCurConns() <= 0) {
//				initBase = true;
//				LogUtil.error("检查basePool发现异常,basePool:"+getBasePoolState());
//			}
//		}
		
		if (checkMain) {
			if (strategyPool == null || strategyPool.getCurConns() <= 0) {
				initStrategy = true;
				LogUtil.error("检查strategyPool发现异常,strategyPool:" + getStrategyPoolState());
			}
		}
//		if (checkLog) {
//			if (logPool == null || logPool.getCurConns() <= 0) {
//				initLog = true;
//				LogUtil.error("检查logPool发现异常,logPool:" + getLogPoolState());
//			}
//		}

		if (initBase || initStrategy || initLog) {
			boolean result = initPool(initBase, initStrategy, initLog);
			StringBuilder sb = new StringBuilder("重新初始化连接池");
			sb.append(result ? "成功" : "失败")
//			.append(",basePoolState:").
//			append(getBasePoolState())
			.append(",strategyPoolState:")
			.append(getStrategyPoolState())
//			.append(",logPoolState：")
//			.append(getLogPoolState())
			;
			LogUtil.error(sb.toString());
		}
	}

	/**
	 * 根据指定属性创建连接池实例.
	 * 
	 * @param props
	 *            连接池属性
	 */
	private static IDBPool createPools(String poolName, String url, String user, String password) {
		int maxconn = 30;
		int maxfllow = 3;
//		if(poolName.equals(BASE_POOL_NAME) && baseDBMaxConn > 0 && baseDBFllow > 0){
//			maxconn = baseDBMaxConn;
//			maxfllow = baseDBFllow;
//		} else 
			if (poolName.equals(STRATEGY_POOL_NAME) && mainDBMaxConn > 0 && mainDBFllow > 0) {
			maxconn = mainDBMaxConn;
			maxfllow = mainDBFllow;
		} 
//			else if (poolName.equals(LOG_POOL_NAME) && logDBMaxConn > 0 && logDBFllow > 0) {
//			maxconn = logDBMaxConn;
//			maxfllow = logDBFllow;
//		}
		try {
//			IDBPool pool = new BoneCPDBPool(poolName, url, DESUtil.decrypt(user), DESUtil.decrypt(password), maxconn, maxfllow);
			IDBPool pool = new BoneCPDBPool(poolName, url, user, password, maxconn, maxfllow);
			String msg = String.format("加载配置连接池:%s,URL:%s完成！", poolName, url);
			LogUtil.info(msg);
			return pool;
		} catch (Exception e) {
			LogUtil.error("创建db连接池失败 poolName : " + poolName, e);
			return null;
		}
	}

	public static void closePools() {
//		if(basePool!=null){
//			basePool.shutdown();
//			basePool=null;
//		}
		if (strategyPool != null) {
			strategyPool.shutdown();
			strategyPool = null;
		}

//		if (logPool != null) {
//			logPool.shutdown();
//			logPool = null;
//		}
		LogUtil.info("数据库连接池关闭成功");
	}
	
	public static void closeStrategyPools() {
		if (strategyPool != null) {
			strategyPool.shutdown();
			strategyPool = null;
		}
		LogUtil.info("Strategy数据库连接池关闭成功");
	}

//	public static Connection getBaseConn() {
//		Connection conn = basePool.getConnection();
//		return conn;
//	}
	
	public static Connection getStrategyConn() {
		Connection conn = strategyPool.getConnection();
		return conn;
	}

//	public static Connection getLogConn() {
//		Connection conn = logPool.getConnection();
//		return conn;
//	}

//	public static String getBasePoolState() {
//		if (basePool != null) {
//			return basePool.getState();
//		}
//		return null;
//	}
	
	public static String getStrategyPoolState() {
		if (strategyPool != null) {
			return strategyPool.getState();
		}
		return null;
	}

//	public static String getLogPoolState() {
//		if (logPool != null) {
//			return logPool.getState();
//		}
//		return null;
//	}

}
